package ee.serge.server;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import ee.serge.service.ArticleService;
import ee.serge.shared.Article;
import ee.serge.shared.BusinessException;
import ee.serge.shared.HandledException;
import ee.serge.shared.LoginException;

@SuppressWarnings("serial")
public class ArticleServiceImpl extends RemoteServiceServlet implements ArticleService {

   @Override
   public void addArticle(Article article) throws HandledException {
      testLoggedIn();
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
         pm.makePersistent(article);
      } catch (Exception e) {
         throw new BusinessException("Error creating article");
      } finally {
         pm.close();
      }
   }

   @Override
   public void updateArticle(Article userArticle) throws HandledException {
      testLoggedIn();
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
         Article baseArticle = pm.getObjectById(Article.class, userArticle.getType());
         baseArticle.setText(userArticle.getText());
      } catch (Exception e) {
         System.out.println(e);
         System.out.println(e.getMessage());
         System.out.println(e.getLocalizedMessage());
         for (StackTraceElement el : e.getStackTrace()) {
            System.out.println(el);
         }
         throw new BusinessException("Error updating article");
      } finally {
         pm.close();
      }
   }
   
   @Override
   public Article getArticle(String type) throws HandledException {
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
         Article baseArticle = pm.getObjectById(Article.class, type);
         pm.close();
         return baseArticle;
      } catch (Exception e) {
         throw new BusinessException("Error getting article");
      } finally {
         if (!pm.isClosed()) {            
            pm.close();
         }
      }
   }
   
   public void testLoggedIn() throws LoginException {
      HttpServletRequest request = getThreadLocalRequest();
      HttpSession session = request.getSession();
      Object attr = session.getAttribute("loggedin");
      try {
         if (attr != null && (Boolean)attr == true) {
            return;
         }
      } catch (ClassCastException e) {}
      throw new LoginException();
   }

}
